import { Injectable } from '@nestjs/common';
import { createTransport, Transporter} from 'nodemailer';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class EmailService {

  transporter: Transporter

  constructor(private configService: ConfigService) {
    this.transporter = createTransport({
      host: this.configService.get('nodemailer_host'),
      port: this.configService.get('nodemailer_port'),
      secure: this.configService.get('nodemailer_secure'),
      auth: {
        user: this.configService.get('nodemailer_auth_user'),
        pass: this.configService.get('nodemailer_auth_pass')
      },
    });
  }

  async sendMail({ to, subject, html }) {
    try {
      await this.transporter.sendMail({
        from: {
          name: this.configService.get('nodemailer_name'),
          address: this.configService.get('nodemailer_auth_user')
        },
        to,
        subject,
        html
      });
    } catch (error) {
      console.error(error);
    }
  }
}